package com.dhruvtaara.beta.controller;

import java.io.IOException;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.dhruvtaara.beta.action.OnlineExamAction;
import com.dhruvtaara.beta.model.viewmodel.ExamQuestion;
import com.dhruvtaara.beta.model.viewmodel.ExamStartInfo;
import com.dhruvtaara.beta.toolset.AppLog;
import com.dhruvtaara.beta.toolset.DefaultEncryption;
import com.dhruvtaara.beta.toolset.WebAction;
import com.google.gson.Gson;

public class OnlineExamServlet extends HttpServlet {
	private static final int USER_ID = 103;
	private static final String USER_ANSWER = "user-answer";
	private static final String VIEW_ONLINE_EXAM_JSP = "/view/onlineExam.jsp";
	private static final String NEXT_QUESTION = "next-question";
	private static final String CHECK_EXAM_AVAILABLE = "check-exam-available";
	private static final String VIEW_EXAM_ABORTED_JSP = "/view/examAborted.jsp";
	private static final String PAGE_REFRESHED = "page-refreshed";
	private static final String REQUEST_TYPE = "requestType";
	private static final String JSON_CONTENT_TYPE = "application/json";
	private static final String EXAM_QUESTION_SESSION_KEY = "exam-questions";

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	/**
	 * 
	 */
	private static final AppLog logger = new AppLog(
			DefaultEncryption.class.getName());

	/**
	 * 
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response) {
		HttpSession session = request.getSession();
		String view = null;
		OnlineExamAction action = new OnlineExamAction();
		view = VIEW_ONLINE_EXAM_JSP;
		
		if (session.getAttribute(PAGE_REFRESHED) == null) {			
			session.setAttribute(PAGE_REFRESHED, "true");
		} else {
			Object examQuestionSession = session
					.getAttribute(EXAM_QUESTION_SESSION_KEY);
			if (examQuestionSession != null) {
				@SuppressWarnings("unchecked")
				List<ExamQuestion> examQuestions = (List<ExamQuestion>) examQuestionSession;

				action.abortExam(true, examQuestions.get(0).getExamId(), USER_ID);
				view = VIEW_EXAM_ABORTED_JSP;
			}
		}

		ServletContext context = getServletContext();
		RequestDispatcher dispatcher = context.getRequestDispatcher(view);
		try {
			dispatcher.forward(request, response);
		} catch (ServletException e) {
			logger.Error(e.toString());
		} catch (IOException e) {
			logger.Error(e.toString());
		}
	}

	/**
	 * 
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response) {

		List<ExamQuestion> questions = null;
		Gson gson = new Gson();
		OnlineExamAction examAction = new OnlineExamAction();
		String requestType = request.getParameter(REQUEST_TYPE);
		response.setContentType(JSON_CONTENT_TYPE);

		if (requestType.equalsIgnoreCase(CHECK_EXAM_AVAILABLE)) {
			ExamStartInfo info = examAction.checkExamAvailable(USER_ID);
			WebAction.writeResponse(response, gson.toJson(info));
		} else {
			HttpSession session = request.getSession();
			Object examQuestions = session
					.getAttribute(EXAM_QUESTION_SESSION_KEY);

			if (examQuestions == null) {
				// assume that the user has logged in and its userId is saved in
				// session
				examQuestions = examAction.getQuestions(USER_ID);
				session.setAttribute(EXAM_QUESTION_SESSION_KEY, examQuestions);
			}

			if (requestType.equalsIgnoreCase(NEXT_QUESTION)) {
				int ordinal = Integer.parseInt(request.getParameter("ordinal"));
				questions = examAction.getNextQuestion(ordinal, examQuestions);

				WebAction.writeResponse(response, gson.toJson(questions));
			}

			if (requestType.equalsIgnoreCase(USER_ANSWER)) {
				int questionId = Integer.parseInt(request
						.getParameter("questionId"));
				String responses = request.getParameter("userAnswers");

				examAction.setUserAnswer(questionId, examAction.getExamId(),
						responses);
			}
		}
	}
}